﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SqlMonitoring.Agent.AgentServiceBase;
using System.Diagnostics;

namespace SqlMonitoring.Agent
{
    public class Performance : AgentSkeleton
    {
        public override int SleepTime()
        {
            return 5; //seconds
        }

        /// <summary>
        /// Use to get recuring data ( state of a service )
        /// </summary>
        public override void ExecuteInternal()
        {                 
            foreach (Counter C in counters)
            {
                if ((!C.Accumulated) && (!C.Calculated))
                {
                    float Val = C.PerfCounter.NextValue();
                    Log.Info(string.Format(C.Format, Val));
                    C.PrevValue = Val;                    
                }
            }
        }

        /// <summary>
        /// Use to configure things, to get onetime things ( memory size ed )
        /// </summary>
        public override void ConfigureInternal()
        {
            GetCountersToMonitor();
            IsConfigured = true;
        }

        /// <summary>
        /// This should get the PerfmonCounters that this class should watch.
        /// </summary>
        private void GetCountersToMonitor()
        {
            //this should come from the database
            counters = new List<Counter>();
            counters.Add(new Counter(1, "Processor", "% Processor Time", "_Total", "{0:##0} % Processor Time", false, false));
            counters.Add(new Counter(2, "Memory", "Available MBytes", "", "{0} MB Available", false, false));
            counters.Add(new Counter(3, "Paging File", "% Usage", "_Total", "{0:##0} % Pagefile in use", false, false));
        }

        private List<Counter> counters;
    }

    public class Counter
    {
        public Counter(int CounterID, string Category, string Counter, string Instance, string Format, bool Accumulated, bool Calculated)
        {
            this.CounterID = CounterID;
            this.PerfCounter = new PerformanceCounter(Category, Counter, Instance, true);
            this.Format = Format;
            this.Accumulated = Accumulated;
            this.Calculated = Calculated;
        }

        public int CounterID;
        public PerformanceCounter PerfCounter;
        public CounterSample PrevSample;
        public float PrevValue;
        public long PrevRaw;
        public DateTime PervTimestamp;
        public string Format;
        public bool Accumulated;
        public bool Calculated;
    }
}
